package tcp.longconnection.client.protocol;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.UUID;

import tcp.longconnection.client.util.SocketUtil;

public class ChatMsgProcotol extends BasicProtocol implements Serializable{

	
	private static final long serialVersionUID = 1L;
	
	public static final int MSGTARGETUUID_LEN = 32;
	public static final int CLIENTVERSION_LEN = 4;

	private String message = "";
	private String selfUUID = "00000000000000000000000000000000";
	private String msgTargetUUID = "00000000000000000000000000000000";
	private int clientVersion = 1;
	public static final String CHATMESCOMMAND = "0001";
	
	@Override
	public String getCommand() {
		return CHATMESCOMMAND;
	}

	public ChatMsgProcotol(String meeeage) {
		this.selfUUID = UUID.randomUUID().toString();
		clientVersion = 1;
	}

	@Override
	public String toString() {
		return "信息:"+message + ",自身UUID:" + selfUUID + ",消息目的UUID:" + msgTargetUUID + ",版本号:"+ clientVersion;
	}
	
	
	
	@Override
	public byte[] getContentData() {
		byte[] pre =  super.getContentData();
		ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
		baos.write(pre, 0, pre.length);
		baos.write(selfUUID.getBytes(), 0, BasicProtocol.SLEFUUID_LEN);
		baos.write(msgTargetUUID.getBytes(), 0, MSGTARGETUUID_LEN);
		baos.write(SocketUtil.intToByte(clientVersion), 0, CLIENTVERSION_LEN);
		byte[] message = getMessage().getBytes();
		baos.write(message, 0, message.length);
		return baos.toByteArray();
	}
	

	@Override
	public int parseBinary(byte[] data) {
		int pos = super.parseBinary(data);
		selfUUID = new String(data, pos, SLEFUUID_LEN);
		pos += SLEFUUID_LEN;
		msgTargetUUID = new String(data, pos, MSGTARGETUUID_LEN);
		pos += MSGTARGETUUID_LEN;
		clientVersion = SocketUtil.byteToInt(data, pos);
		pos += CLIENTVERSION_LEN;
		try {
			message = new String(data, pos, data.length, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return pos;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getSelfUUID() {
		return selfUUID;
	}

	public void setSelfUUID(String selfUUID) {
		this.selfUUID = selfUUID;
	}

	public String getMsgTargetUUID() {
		return msgTargetUUID;
	}

	public void setMsgTargetUUID(String msgTargetUUID) {
		this.msgTargetUUID = msgTargetUUID;
	}

	public int getClientVersion() {
		return clientVersion;
	}

	public void setClientVersion(int clientVersion) {
		this.clientVersion = clientVersion;
	}
	
	
}
